package com.wenhai.leetcode.linkedList;

/**
 * @ClassName _61旋转链表
 * @Description https://leetcode-cn.com/problems/rotate-list/
 * @Author 谢文海
 * @Date 2021/3/27 19:31
 * @Version 1.0
 **/
public class _61旋转链表 {

    public ListNode rotateRight(ListNode head, int k) {
        if (head != null && k > 1) {
            int size = k % size(head);
            if (size != 0) {
                for (int i = 1; i <= size; i++) {
                    ListNode trailer = deleteTrailer(head);
                    trailer.next = head;
                    head = trailer;
                }
            }

        }
        return head;

    }

    private int size(ListNode node) {
        int size = 0;
        while (node != null) {
            size++;
            node = node.next;
        }
        return size;
    }

    private ListNode deleteTrailer(ListNode node) {
        ListNode prev = null;
        while (node != null && node.next != null) {
            prev = node;
            node = node.next;
        }
        if (prev != null) {
            prev.next = null;
        }
        return node;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        new _61旋转链表().rotateRight(head, 2);
    }
}
